package com.irrigation.config;

import com.irrigation.model.User;
import com.irrigation.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;




@Component
@RequiredArgsConstructor
@Slf4j
public class DataInitializer implements CommandLineRunner {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) {
        // 初始化管理员用户
        if (!userRepository.existsByUsername("admin")) {
            log.info("Creating admin user");

            User admin = User.builder()
                    .username("admin")
                    .password(passwordEncoder.encode("admin123"))
                    .email("admin@example.com")
                    .firstName("系统管理员")
                    .lastName("")
                    .role(User.Role.ADMIN)
                    .active(true)
                    .build();

            userRepository.save(admin);
        }

        // 初始化普通用户
        if (!userRepository.existsByUsername("user")) {
            log.info("Creating regular user");

            User user = User.builder()
                    .username("user")
                    .password(passwordEncoder.encode("user123"))
                    .email("user@example.com")
                    .firstName("普通用户")
                    .lastName("")
                    .role(User.Role.USER)
                    .active(true)
                    .build();

            userRepository.save(user);
        }
    }
}
